//
//  ViewController.m
//  iOS-Network-Basic
//
//  Created by 吴开杰 on 2020/3/10.
//  Copyright © 2020 吴开杰. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageNet;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.view.backgroundColor = [UIColor purpleColor];
    
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self networking];
    
}



- (void)networking{
    
    
    // 如果使用http，而不是https，需要在info.plist添加如下配置：
//    <key>NSAppTransportSecurity</key>
//    <dict>
//        <key>NSAllowsArbitraryLoads</key>
//        <true/>
//    </dict>
    
    // 1.创建URL
    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com/img/superlogo_c4d7df0a003d3db9b65e9ef0fe6da1ec.png"];
    // 2.创建一个网络请求
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
    // 3.创建一个网络管理
    NSURLSession *session = [NSURLSession sharedSession];
    // 4.创建一个网络任务
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        
        if (error) {
            
            NSLog(@"有错误");
            
        }
        
        else {
            
            
            //需要转换成NSHTTPURLResponse
            NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;

            NSLog(@"%ld", (long)res.statusCode);
            
            
            // 网络请求的回调，默认是在子线程中的，更新UI需要在主线程中
            dispatch_async(dispatch_get_main_queue(), ^{
                self.imageNet.image = [UIImage imageWithData:data];
                
            });
            
            
        }
        
    }];
    // 5.开启网络任务
    [task resume];
    
}


@end
